package com.example.springboot_shopping.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_shopping.entity.User;
import com.example.springboot_shopping.mapper.UserMapper;
import com.example.springboot_shopping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.List;
import java.util.Date;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override
    public User findById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public boolean register(User user) {
        // 密码加密（示例）
        user.setUpassword(DigestUtils.md5DigestAsHex(user.getUpassword().getBytes()));
        user.setUregistertime(new Date());
        user.setUstatus(0); // 0表示未删除
        return userMapper.insert(user) == 1;
    }

    @Override
    public boolean update(User user) {
        return userMapper.updateById(user) == 1;
    }

    @Override
    public boolean deleteById(Integer id) {
        return userMapper.deleteById(id) == 1;
    }

    @Override
    public User login(String username, String password) {
        // 密码加密后查询
        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("u_name", username).eq("u_password", encryptedPwd);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public Page<User> findByPage(Integer pageNum, Integer pageSize) {
        // 创建分页对象，pageNum为当前页码，pageSize为每页记录数
        Page<User> page = new Page<>(pageNum, pageSize);
        // 执行分页查询（参数1：分页条件，参数2：查询条件，null表示无额外条件）
        return userMapper.selectPage(page, null);
    }
}